package com.talking.view.component;

import com.talking.pojo.ChatMsg;
import com.talking.pojo.SystemVariable;
import com.talking.tool.MsgToPane;
import com.talking.view.componentpojo.ColorObj;
import sun.font.FontDesignMetrics;

import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ChatBlock extends JLabel {
    private HeadImage headImage;
    private JLabel nameLabel;
    private JLabel timeLabel;
    private BlockPanel popBlock;
    private JIMSendTextPane textPane;
    private SpringLayout springLayout;

//    private int height = 0;

    private final int headSize = 40;
    private final int pad = 10;
    private Color color = ColorObj.mainThemeColor;

    public ChatBlock(ChatMsg chatMsg){
        super();
        headImage = new HeadImage(headSize,"/u100005",null);
        nameLabel = new JLabel();
        timeLabel = new JLabel();
        popBlock = new BlockPanel();
        textPane = new JIMSendTextPane();
        springLayout = new SpringLayout();


        nameLabel.setText(chatMsg.getSender().getUser_name());
        nameLabel.setPreferredSize(new Dimension(50,40));
        nameLabel.setForeground(ColorObj.LIGHT_WHITE5);

        timeLabel.setText(chatMsg.getSendTime());
        timeLabel.setForeground(ColorObj.LIGHT_WHITE5);


        popBlock.setAllColor(color,color,color);
        String text = chatMsg.getContent();



        textPane.setSize(300, textPane.getPreferredSize().height);
        this.insertContent(textPane,text);
//            textPane.setText(text);
        int hei = textPane.getPreferredSize().height;

        textPane.setSize(300, hei);


        if (hei<=21||hei==42){
            JIMSendTextPane tempPane = new JIMSendTextPane();
            tempPane.setSize(new Dimension(tempPane.getPreferredSize().width,hei));
            this.insertContent(tempPane,text);
            tempPane.setSize(new Dimension(tempPane.getPreferredSize().width,hei));

            textPane.setPreferredSize(new Dimension(tempPane.getPreferredSize().width,hei));
        }
        else
            textPane.setPreferredSize(new Dimension(300,textPane.getPreferredSize().height));


        System.out.println("高度是："+textPane.getPreferredSize().getHeight());

        textPane.setEditable(false);
        textPane.setForeground(ColorObj.MAIN_BACKGROUND);
        textPane.setBackground(new Color(0,0,0,0));
        textPane.setOpaque(false);

        if (chatMsg.getSender().getUser_id()!= SystemVariable.getCurrentUser().getUser_id()) {
            this.setWestSpring(headImage, this, pad, this, pad);
            this.setWestSpring(nameLabel, headImage, headImage.getPreferredSize().height, this, pad);
            this.setWestSpring(timeLabel, this, pad, headImage, (int) headImage.getPreferredSize().getWidth() + pad);
            this.setWestSpring(popBlock, timeLabel, timeLabel.getPreferredSize().height + pad, headImage, (int) headImage.getPreferredSize().getWidth() + pad);
        }else{
            color = ColorObj.Spot_Palette1;
            popBlock.setAllColor(color,color,color);

            this.setEastSpring(headImage,this,pad,this,-pad);
            this.setEastSpring(nameLabel, headImage, headImage.getPreferredSize().height, this, -pad);
            this.setEastSpring(timeLabel, this, pad, headImage, -((int) headImage.getPreferredSize().getWidth() + pad));
            this.setEastSpring(popBlock, timeLabel, timeLabel.getPreferredSize().height + pad, headImage, -((int) headImage.getPreferredSize().getWidth() + pad + 2));
        }

        this.setLayout(springLayout);
        this.add(headImage);
        this.add(nameLabel);
        this.add(timeLabel);
        this.add(popBlock);

        popBlock.addComponents(textPane);
        this.setPreferredSize(new Dimension(1,(int)popBlock.getPreferredSize().getHeight()+2*pad+nameLabel.getPreferredSize().height));

        int count = textPane.getDocument().getDefaultRootElement().getElementCount();
        System.out.println("行数是："+count);
    }

    //插入文字与表i情报
    private void insertContent(JIMSendTextPane pane,String content){
        Document doc = pane.getDocument();
        SimpleAttributeSet attrSet = new SimpleAttributeSet();          //格式对象
        StyleConstants.setForeground(attrSet, ColorObj.MAIN_BACKGROUND);
//
//
//        //用户名与时间设置
//
        try {

            //消息内容处理，主要是将表情包与文字分开
            //判断信息中，是否有表情包存在: 你好，你在干嘛[害羞]，今天来学校不[呆]
            File imagePath = new File("image/chat/emjio");
            File[] allPng = imagePath.listFiles();
            java.util.List<String> emjioName = new ArrayList();           //所有的表情包名字
            List<EmjioText> emjioTexts = new ArrayList();       //记录表情包文字的列表

            for (File file : allPng) {
                emjioName.add(file.getName().replace(".png",""));
            }


            String tempText = content;
            StringBuffer tempBuffer;
            for (int i = 0; i < emjioName.size(); i++) {
                while(tempText.contains(emjioName.get(i))){
                    int index = tempText.indexOf(emjioName.get(i));
                    String code = emjioName.get(i);
                    int length = emjioName.get(i).length();

                    emjioTexts.add(new EmjioText(index,code,length));
                    tempBuffer = new StringBuffer(tempText);
                    String replaceTemp = "";

                    for (int j = 0; j < length; j++) {
                        replaceTemp +="u";
                    }

                    tempBuffer.replace(index,index+length,replaceTemp);
                    tempText = tempBuffer.toString();
                }
            }

            EmjioText[] emjioTextsArray = new EmjioText[emjioTexts.size()];

            //表情包列表转换成为数组
            int a = 0;
            for (EmjioText emjioText : emjioTexts) {
                emjioTextsArray[a] = emjioText;
                a++;
            }

            //对数组进行排序
            for (int i=0;i<emjioTextsArray.length-1;i++){
                for (int j=0;j<emjioTextsArray.length-1-i;j++){
                    EmjioText temp = null;
                    if (emjioTextsArray[j].index>emjioTextsArray[j+1].index) {
                        temp = emjioTextsArray[j];
                        emjioTextsArray[j] = emjioTextsArray[j+1];
                        emjioTextsArray[j+1] = temp;
                    }
                }
            }

            for (int i = 0; i < emjioTextsArray.length; i++) {
                content = content.replace(emjioTextsArray[i].code,"<&#&>");
            }

            if (emjioTextsArray.length!=0&&emjioTextsArray[0].index==0)
                content = content.substring(5);

            String[] textMsg = content.split("<&#&>");

            //于此，表情包与文字都分成了数组
            int eLength = emjioTextsArray.length;
            int tLength = textMsg.length;

//            StyleConstants.setFontSize(attrSet, 18);
            for (int i = 0; i < (eLength>tLength?eLength:tLength); i++) {
                if (emjioTextsArray.length!=0&&emjioTextsArray[0].index!=0){
                    //先插入文字
                    if (i<textMsg.length){
                        doc.insertString(doc.getLength(), textMsg[i], attrSet);
                    }

                    if (i<emjioTextsArray.length){
                        pane.setCaretPosition(doc.getLength());
                        pane.insertIcon(new ImageIcon("image/chat/emjio/"+emjioTextsArray[i].code+".png"));
                    }
                }else {
                    //先插入表情包

                    if (i<emjioTextsArray.length){
                        pane.setCaretPosition(doc.getLength());
                        pane.insertIcon(new ImageIcon("image/chat/emjio/"+emjioTextsArray[i].code+".png"));
                    }

                    if (i<textMsg.length){
                        doc.insertString(doc.getLength(), textMsg[i], attrSet);
                    }

                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void setWestSpring(JComponent currentComponent,JComponent north,int northPad,JComponent west,int westPad){
        springLayout.putConstraint(SpringLayout.NORTH,currentComponent,northPad,SpringLayout.NORTH,north);
        springLayout.putConstraint(SpringLayout.WEST,currentComponent,westPad,SpringLayout.WEST,west);
    }
    private void setEastSpring(JComponent currentComponent,JComponent north,int northPad,JComponent east,int eastPad){
        springLayout.putConstraint(SpringLayout.NORTH,currentComponent,northPad,SpringLayout.NORTH,north);
        springLayout.putConstraint(SpringLayout.EAST,currentComponent,eastPad,SpringLayout.EAST,east);
    }

    //用来存储表情文字
    private class EmjioText{
        private int index;
        private String code;
        private int length;

        public EmjioText(int index, String code, int length) {
            this.index = index;
            this.code = code;
            this.length = length;
        }

        @Override
        public String toString() {
            return "EmjioText{" +
                    "index=" + index +
                    ", code='" + code + '\'' +
                    ", length=" + length +
                    '}';
        }
    }
}
